//
//  KeyboardViewController.m
//  dangdang
//
//  Created by air on 15/12/15.
//  Copyright © 2015年 luweijie. All rights reserved.
//

#import "KeyboardViewController.h"
#import "BillPageViewController.h"
#import "BillViewController.h"
#import "LVRecordTool.h"
#import "MapViewController.h"
#import "OrderDetailsViewController.h"
#import "ASIFormDataRequest.h"

@interface KeyboardViewController ()<UUDatePickerDelegate>

@property (nonatomic) float count;
@property (nonatomic, copy) NSString * dateString;
/** 录音工具 */
@property (nonatomic, strong) LVRecordTool *recordTool;
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic) double timeout;
@property (nonatomic) NSInteger time;

@end

@implementation KeyboardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self againBill];
    
    [self updateUI];
    
    [self dateViewDisplay];
    
    self.dateTopView.hidden = YES;
    self.dateView.hidden = YES;
    
    self.count = 0;
    
    self.title = @"发单";
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    for (UIView * view in self.viewArray) {
        view.layer.borderWidth = 1;
        view.layer.borderColor = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.5] CGColor];
        view.layer.cornerRadius = 8;
    }
    
    MAMapPoint point1 = MAMapPointForCoordinate(_coor1);
    MAMapPoint point2 = MAMapPointForCoordinate(_coor2);
    //2.计算距离
    CLLocationDistance distance = MAMetersBetweenMapPoints(point1,point2);
//    NSLog(@"distance = %f", distance);
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
}

- (void)againBill{
    if ([_again isEqualToString:@"again"]) {
        _goodsNameTextField.text = _detailsViewController.detailsObject.item_name;
        _locationLabel.text = _detailsViewController.detailsObject.location_name;
        _locationLabel.textColor = [UIColor blackColor];
        _priceTextField.text = _detailsViewController.detailsObject.item_price;
        _kgTextField.text = _detailsViewController.detailsObject.item_weight;
        _distanceLabel.text = _detailsViewController.detailsObject.distance;
        _chooseTimeLabel.text = _detailsViewController.detailsObject.reach_time;
        _chooseTimeLabel.textColor = [UIColor blackColor];
    }
}

- (void)updateUI{
    
    if (self.view.frame.size.height == 736) {
        self.height.constant += 72;
    }
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    
    [self.view addGestureRecognizer:singleTap];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapPush:)];
    tap.numberOfTapsRequired = 1;
    [_mapView addGestureRecognizer:tap];
    UITapGestureRecognizer * designatedtap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapPush:)];
    tap.numberOfTapsRequired = 1;
    [_designatedMapView addGestureRecognizer:designatedtap];
    
    _timeout = _homeViewController.currentTime * 2; //倒计时时间
    _time = 0;
    
    _recordTool = [LVRecordTool sharedRecordTool];
    _recorderTimeLabel.text = [NSString stringWithFormat:@"%.0lf\"", _homeViewController.currentTime];
    
    _speechView.layer.cornerRadius = 8;
    
    if ([self.textOrSpeech isEqualToString:@"text"]) {
        self.goodsNameConstraint.constant -= 92;
        [self.speechView removeFromSuperview];
    }
    
    self.demandButton.layer.cornerRadius = 10;
    self.demandButton.layer.borderWidth = 0.5;
    self.demandButton.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    
    UIFont *font = [UIFont systemFontOfSize:17];
    NSString *dollarSignText = @"￥";
    CGSize size = [dollarSignText sizeWithAttributes:@{NSFontAttributeName: font}];
    UILabel *dollarSignLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, ceilf(size.width), 44)];
    dollarSignLabel.font = font;
    dollarSignLabel.text = dollarSignText;
    dollarSignLabel.textColor = [UIColor orangeColor];
    dollarSignLabel.textAlignment = NSTextAlignmentRight;
    _markupTextField.leftView = dollarSignLabel;
    _markupTextField.leftViewMode = UITextFieldViewModeAlways;
    
    _goodsNameTextField.delegate = self;
    _priceTextField.delegate = self;
    _kgTextField.delegate = self;
    _markupTextField.delegate = self;
    
    _kgTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    _priceTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    _markupTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
}

-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer

{
    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField.tag == 1 || textField.tag == 2 || textField.tag == 3) {
        //控制长度
        if(range.location>=20)
            return NO;
        
        const char * ch=[string cStringUsingEncoding:NSUTF8StringEncoding];
        if(*ch == 0)
            return YES;
        //字符0－9 和 .
        if( *ch != 46 && ( *ch<48 || *ch>57) )
            return NO;
        
        //有了小数点
        if([textField.text rangeOfString:@"."].length==1)
        {
            NSUInteger length=[textField.text rangeOfString:@"."].location;
            
            //小数点后面两位小数 且不能再是小数点
            if([[textField.text substringFromIndex:length] length]>3 || *ch ==46)   //3表示后面小数位的个数。。
                
                return NO;
        }
    }
    return YES;
}

- (IBAction)playRecorder:(UIButton *)sender {    
    if (_recorderButton.tag == 0) {
        [self.recordTool playRecordingFile];
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(voiceChange:) userInfo:nil repeats:YES];
        _recorderButton.tag = 1;
    }else{
        [self.recordTool stopPlaying];
        [_timer invalidate];
        [_voiceButton setImage:[UIImage imageNamed:@"hk_voice2.png"] forState:UIControlStateNormal];
        _timeout = _homeViewController.currentTime * 2;
        _time = 0;
        _recorderButton.tag = 0;
    }
}

- (void)voiceChange:(NSTimer *)timer{
    if(_timeout<=0){ //倒计时结束，关闭
        [_voiceButton setImage:[UIImage imageNamed:@"hk_voice2.png"] forState:UIControlStateNormal];
        [_timer invalidate];
        _timeout = _homeViewController.currentTime * 2;
        _time = 0;
        _recorderButton.tag = 0;
    }else{
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:1];
        [_voiceButton setImage:[UIImage imageNamed:imageArray[_time % 3]] forState:UIControlStateNormal];
        [UIView commitAnimations];
        _time ++;
        _timeout--;
    }
}

- (void)mapPush:(UITapGestureRecognizer *)tapGestureRecognizer{
    UIView * view = (UIView *)tapGestureRecognizer.view;
    MapViewController * mapboardVC = [[UIStoryboard storyboardWithName:@"MapViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"MapViewController"];
    mapboardVC.KeyboardViewController = self;
    if (view.tag == 0) {
        mapboardVC.location = @"designated";
    }else{
        mapboardVC.location = @"location";
    }
    
    [self.navigationController pushViewController:mapboardVC animated:YES];
}

- (void)dateViewDisplay{
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewDisplay)];
    tap.numberOfTapsRequired = 1;
    [self.chooseTimeLabel addGestureRecognizer:tap];
    self.chooseTimeLabel.userInteractionEnabled = YES;
}

- (void)viewDisplay{
    self.dateTopView.hidden = NO;
    self.dateView.hidden = NO;
    
    UUDatePicker *datePicker= [[UUDatePicker alloc]initWithframe:CGRectMake((self.view.bounds.size.width - 320) / 2, 0, 320, 200)
                                                        Delegate:self
                                                     PickerStyle:UUDateStyle_YearMonthDayHourMinute];
    [self.dateView addSubview:datePicker];
}

#pragma mark - UUDatePicker's delegate
- (void)uuDatePicker:(UUDatePicker *)datePicker
                year:(NSString *)year
               month:(NSString *)month
                 day:(NSString *)day
                hour:(NSString *)hour
              minute:(NSString *)minute
             weekDay:(NSString *)weekDay
{
    self.dateString = [NSString stringWithFormat:@"%@-%@-%@ %@:%@:00",year,month,day,hour,minute];
}

- (IBAction)cancelOrConfirmBtn:(UIButton *)sender {
    if (sender.tag == 0) {
        self.dateTopView.hidden = YES;
        self.dateView.hidden = YES;
    }else{
        self.chooseTimeLabel.text = self.dateString;
        self.chooseTimeLabel.textColor = [UIColor blueColor];
        self.dateTopView.hidden = YES;
        self.dateView.hidden = YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)addAndSubtractButton:(UIButton *)sender {
    self.count = [_kgTextField.text floatValue];
    if (sender.tag == 0) {
        if (self.count < 1) {
            return;
        }else{
            self.count --;
        }
        self.kgTextField.text = [NSString stringWithFormat:@"%.1f", self.count];
    }else{
        self.count  ++;
        self.kgTextField.text = [NSString stringWithFormat:@"%.1f", self.count];
    }
}
- (IBAction)demandBtn:(UIButton *)sender {
    if ([_goodsNameTextField.text isEqual:nil] || [_goodsNameTextField.text isEqualToString:@""]) {
        [self alertViewShowWithAlertString:@"物品名称不能为空"];
        return;
    }
    if ([_locationLabel.text isEqual:nil] || [_locationLabel.text isEqualToString:@""] || [_locationLabel.text isEqualToString:@"请选择地点"]) {
        [self alertViewShowWithAlertString:@"送往地点不能为空"];
        return;
    }
    if ([_priceTextField.text isEqual:nil] || [_priceTextField.text isEqualToString:@""]) {
        [self alertViewShowWithAlertString:@"物品价格不能为空"];
        return;
    }
    if ([_chooseTimeLabel.text isEqual:nil] || [_chooseTimeLabel.text isEqualToString:@""] || [_chooseTimeLabel.text isEqualToString:@"选择时间"]) {
        [self alertViewShowWithAlertString:@"请选择时间"];
        return;
    }
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:@"lvRecord.caf"];
    NSData * data = [NSData dataWithContentsOfFile:filePath];
    
    NSString * userID = userObject.userID;
    NSString * goodsNameString = _goodsNameTextField.text;
    NSString * priceString = _priceTextField.text;
    NSString * locationString = _locationLabel.text;
    NSString * longitudeString = _lng;
    NSString * latitudeString = _lat;
    NSString * contentString = _markupTextField.text;
    NSString * distanceString = _distanceLabel.text;
    NSString * timeString = _chooseTimeLabel.text;
    NSString * token = userObject.accessToken;
    NSString * designatedString = _designatedLabel.text;
    NSString * urlString = [NSString stringWithFormat:@"%@%@",URLDoman,@"order/create_order"];
    NSURL *url = [NSURL URLWithString:urlString];
    
    if (userID) {
        ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:url];
        request.tag = 0x01;
        request.delegate = self;
        [request setRequestMethod:@"POST"];
        [request setTimeOutSeconds:90];
        [request addPostValue:token forKey:@"token"];
        [request addPostValue:userID forKey:@"uid"];
        [request addPostValue:goodsNameString forKey:@"item_name"];
        [request addPostValue:priceString forKey:@"item_price"];
        [request addPostValue:locationString forKey:@"location_name"];
        [request addPostValue:longitudeString forKey:@"location_lng"];
        [request addPostValue:latitudeString forKey:@"location_lat"];
        [request addPostValue:contentString forKey:@"remark"];
        [request addPostValue:timeString forKey:@"reach_time"];
        if ([distanceString isEqualToString:@"自动计算"]) {
            [request addPostValue:@"" forKey:@"distance"];
        }else{
            [request addPostValue:distanceString forKey:@"distance"];
        }
        [request addPostValue:designatedString forKey:@"item_buy_location_name"];
        if (cityObject.cityID == nil) {
            [request addPostValue:@"2" forKey:@"cityid"];
        }else{
            [request addPostValue:cityObject.cityID forKey:@"cityid"];
        }
        if ([_textOrSpeech isEqualToString:@"text"]) {
            [request addData:nil forKey:@"attach"];
        }else if ([_textOrSpeech isEqualToString:@"speech"]){
            [request addData:data forKey:@"attach"];
        }
        [request startAsynchronous];
    }
    
//    if (userID) {
//        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
//        [params setObject:token forKey:@"token"];
//        [params setObject:userID forKey:@"uid"];
//        [params setObject:goodsNameString forKey:@"item_name"];
//        [params setObject:priceString forKey:@"item_price"];
//        [params setObject:locationString forKey:@"location_name"];
//        [params setObject:longitudeString forKey:@"location_lng"];
//        [params setObject:latitudeString forKey:@"location_lat"];
//        [params setObject:contentString forKey:@"remark"];
//        [params setObject:timeString forKey:@"reach_time"];
//        if ([distanceString isEqualToString:@"自动计算"]) {
//            [params setObject:@"" forKey:@"distance"];
//        }else{
//            [params setObject:distanceString forKey:@"distance"];
//        }        
//        [params setObject:designatedString forKey:@"item_buy_location_name"];
//        if (cityObject.cityID == nil) {
//            [params setObject:@"2" forKey:@"cityid"];
//        }else{
//            [params setObject:cityObject.cityID forKey:@"cityid"];
//        }
//        [params setObject:data forKey:@"attach"];
//        
//        [self postRequestWithMethodName:@"order/create_order" andParams:params andSender:nil];
//        [LoadingView showInView:self.view image:nil info:@"通讯中，请稍候..." animated:YES modeled:YES autoHide:NO];
//    }
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableContainers error:nil];
    NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
    
    if ([code isEqualToString:@"0"]) {
        userObject.ordID = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"order_id"]];
        
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.userID;
        NSString * orderIDString = userObject.ordID;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        [params setObject:orderIDString forKey:@"order_id"];
        
        [self postRequestWithMethodName:@"order/get_order" andParams:params andSender:nil];
        
        userObject.orderStatus = @"sucess";
    }else{
        [self alertViewShowWithAlertString:@"发布失败"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{

}

//解析数据
- (NSMutableDictionary *)paramrequest:(ASIHTTPRequest *)request
{
    NSString *resultDict=[[NSString alloc] initWithData:request.responseData encoding:request.responseEncoding] ;
    NSDictionary *dict=[request userInfo];
    
    NSMutableDictionary *paramsDict=[[NSMutableDictionary alloc] init];
    if(resultDict!=nil)
    {
        [paramsDict setObject:resultDict forKey:@"Data"];
    }
    for(NSString *key in [dict allKeys])
    {
        [paramsDict setObject:[dict objectForKey:key] forKey:key];
    }
    return paramsDict;
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    NSString * urlString = [NSString stringWithFormat:@"%@", task.currentRequest.URL];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
//        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/get_order"]]){
            BillPageViewController *pageController = [[BillPageViewController alloc] init];
            NSArray *viewControllerClasses = @[[BillViewController class], [OrderDetailsViewController class]];
            NSArray *titles = @[@"订单状态", @"订单详情"];
            pageController.viewControllerClasses = viewControllerClasses;
            pageController.titles = titles;
            pageController.menuItemWidth = self.view.frame.size.width / 2;
            pageController.menuViewStyle = WMMenuViewStyleLine;
            pageController.titleSizeSelected = 15.0;
            pageController.titleName = @"我的订单";
            
            userObject.array = [[result objectForKey:@"retmsg"] objectForKey:@"streams"];
            
            [self.navigationController pushViewController:pageController animated:YES];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
